package org.pidan.basic.multiThread;

import org.pidan.DateUtils;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * {@code @description}: Condition 与Lock配合完成等待通知机制
 * {@code @author}: huangyuxin
 * {@code @date}: 2023-12-13
 */
public class ReenTrantLockCondition {

    public static ReentrantLock reentrantLock = new ReentrantLock();

    public static Condition condition = reentrantLock.newCondition();

    public static class T1 extends Thread {
        @Override
        public void run() {

            System.out.println(this.getName() + "  时间：" + DateUtils.getNowDateTime() + "  准备获取锁");

            reentrantLock.lock();

            try {
                System.out.println(this.getName() + "  时间：" + DateUtils.getNowDateTime() + "  获取锁");
                condition.await();

                //2秒自动返回
//                condition.await(2, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                reentrantLock.unlock();
            }

            System.out.println(this.getName() + "  时间：" + DateUtils.getNowDateTime() + "  释放结束");

        }
    }

    public static class T2 extends Thread {
        @Override
        public void run() {
            System.out.println(this.getName() + "  时间：" + DateUtils.getNowDateTime() + "  准备获取锁");

            reentrantLock.lock();

            try {
                System.out.println(this.getName() + "  时间：" + DateUtils.getNowDateTime() + "  获取锁");
                condition.signal();
                System.out.println(this.getName() + "  时间：" + DateUtils.getNowDateTime() + "  唤醒");

                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(this.getName() + "  时间：" + DateUtils.getNowDateTime() + "  释放锁");
            } finally {
                reentrantLock.unlock();
            }

            System.out.println(this.getName() + "  时间：" + DateUtils.getNowDateTime() + "  释放结束");
        }

    }

    public static void main(String[] args) throws InterruptedException {
        T1 t1 = new T1();
        t1.setName("tt11");
        t1.start();

        TimeUnit.SECONDS.sleep(5);

        T2 t2 = new T2();
        t2.setName("tt22");
        t2.start();
    }
}



